<template>
    <div>
        <vxe-table
            :header-cell-style="{ backgroundColor: '#e8f3ff', padding: '4px 0' }"
            :footer-cell-style="{ backgroundColor: '#e8f3ff', padding: '4px 0' }"
            :data="tableData"
            :key="tableKey + 'tableKey'"
            v-loading="loading"
            border
            stripe
            resizable
            :auto-resize="true"
            show-footer
            :footer-method="getSummaries"
            :sort-config="{
                defaultSort: { field: sortProp, order: sortOrder, orders: ['desc', 'asc', null] },
                remote: true,
            }"
            highlight-current-row
            @sort-change="changeTableSort"
            :resizable-config="{ minWidth: '60' }"
            ref="table"
            show-header-overflow="tooltip"
            show-footer-overflow="tooltip"
            header-align="center"
        >
            <vxe-column
                v-for="item in showFieldList"
                :field="item.id"
                :title="item.content"
                :key="item.content"
                :align="getAlign(item)"
                :min-width="item.minWidth || '105px'"
                show-overflow="tooltip"
                sortable
            >
                <template slot-scope="scope">
                    <span v-if="['currentAmount', 'beginAmount', 'lastPrice', 'marketValue'].includes(item.id)">
                        {{ numberFormat(scope.row[item.id], 2) || '--' }}
                    </span>
                    <span v-else>
                        {{ scope.row[item.id] === 0 || (scope.row[item.id] && (scope.row[item.id] + '').trim()) ? scope.row[item.id] : '--' }}
                    </span>
                </template>
            </vxe-column>
        </vxe-table>
        <risk-pagination :paging="page" @page-change="pageRet"></risk-pagination>

        <RiskTableLayout
            title="页面布局"
            :visible.sync="layoutDialog"
            :field-list="tableColumns"
            :selected-field-list="selectedFieldList"
            :fixed-field-list="fixedFieldList"
            :reset-no-selected-field-list="resetNoSelectedFieldList"
            table-name="TN_ASSET_POSITION"
            @on-submit="onSubmit"
        />
    </div>
</template>
<script lang="ts">
import RiskPagination from '@/common/components/risk-pagination.vue';
import RiskTableLayout from '@/common/components/risk-table-layout.vue';
import { numberFormat } from '@/utils/tools';
import { Component, Vue, Prop, Watch } from 'vue-property-decorator';
export interface pages {
    total?: number;
    pageSize?: number;
    currentPage?: number;
}
@Component({ name: 'Position', components: { RiskTableLayout, RiskPagination } })
export default class Position extends Vue {
    @Prop()
    transData: any;

    numberFormat = numberFormat;

    resetNoSelectedFieldList = [];

    layoutDialog: boolean = false; // 布局显示值

    showFieldList: any[] = []; // 展示字段

    selectedFieldList: any[] = []; // 已选字段

    fixedFieldList: any[] = [{ id: 'fundId', content: '产品序号' }];

    tableData: any[] = []; // 表格数据

    summary: any = {}; // 汇总行

    tableKey: number = -1;

    loading: boolean = false; // 页面渲染

    private sortProp: string = 'fundId'; // 排序字段

    private sortOrder: string = 'asc'; // 排序方式

    sort: string = 'L_FUND_ID ASC'; // 默认排序字段

    private page: pages = {
        currentPage: 1,
        pageSize: 10,
        total: 0,
    };

    // 表格字段
    tableColumns = [
        {
            content: '产品序号',
            id: 'fundId',
            align: 'left',
        },
        {
            content: '产品名称',
            id: 'fundName',
            align: 'left',
        },
        {
            content: '资产单元编号',
            id: 'assetId',
            minWidth: '130px',
            align: 'left',
        },
        {
            content: '资产单元名称',
            id: 'assetName',
            align: 'left',
            minWidth: '130px',
        },
        {
            content: '组合编码',
            id: 'basecombiId',
            align: 'left',
        },
        {
            content: '组合名称',
            id: 'combiName',
            align: 'left',
        },
        {
            content: '证券代码',
            id: 'stockCode',
            align: 'left',
        },
        {
            content: '证券名称',
            id: 'stockNameSt',
            align: 'left',
        },
        {
            id: 'stockType',
            content: '证券类别',
            align: 'center',
        },
        {
            id: 'assetClass',
            content: '资产分类',
            align: 'center',
        },
        {
            id: 'companyId',
            content: '发行人编码',
            align: 'left',
            minWidth: '120px',
        },
        {
            id: 'issuerName',
            content: '发行人名称',
            align: 'left',
            minWidth: '120px',
        },
        {
            content: '交易市场',
            id: 'marketName',
            align: 'center',
        },
        {
            content: '持仓标志',
            id: 'positionFlag',
            align: 'center',
        },
        {
            content: '投资类型',
            id: 'investType',
            align: 'center',
        },
        {
            content: '期初持仓数量',
            id: 'beginAmount',
            minWidth: '140px',
        },
        {
            content: '当前持仓数量',
            id: 'currentAmount',
            minWidth: '130px',
        },
        {
            content: '最新价',
            id: 'lastPrice',
        },
        {
            content: '市值金额',
            id: 'marketValue',
            // 当前持仓数量*最新价
        },
    ];

    // 排序字段
    sortableObj = {
        assetId: 'L_ASSET_ID',

        assetName: 'VC_ASSET_NAME',

        basecombiId: 'L_BASECOMBI_ID',

        beginAmount: 'L_BEGIN_AMOUNT',

        combiName: 'VC_COMBI_NAME',

        currentAmount: 'L_CURRENT_AMOUNT',

        fundId: 'L_FUND_ID',

        fundName: 'VC_FUND_NAME',

        investType: 'C_INVEST_TYPE_CODE',

        lastPrice: 'EN_LAST_PRICE',

        marketName: 'VC_MARKET_NAME',

        marketValue: 'marketValue',

        positionFlag: 'C_POSITION_FLAG_CODE',

        stockCode: 'VC_INTER_CODE',

        stockNameSt: 'VC_STOCK_NAME',
        assetClass: 'C_ASSET_CLASS_CODE',
        stockType: 'C_STOCK_TYPE_CODE',
        companyId: 'L_COMPANY_ID',
        issuerName: 'VC_ISSUER_NAME',
    };
    isFirst: boolean = true;
    currentRecord: any = {};
    @Watch('transData', { immediate: true, deep: true })
    async handleTab(nowVal, oldVal) {
        if (nowVal['activeTab'] == 'Position') {
            this.layoutDialog = nowVal.detailLayoutDialog;
            if (this.isFirst) {
                await this.queryLayout();
                this.getPostitionTableData();
                this.isFirst = false;
            } else if (
                !oldVal ||
                JSON.stringify(oldVal.clickRow) !== JSON.stringify(nowVal.clickRow) ||
                JSON.stringify(nowVal.clickRow) !== JSON.stringify(this.currentRecord)
            ) {
                this.currentRecord = JSON.parse(JSON.stringify(nowVal.clickRow));
                !oldVal && (await this.queryLayout());
                this.getPostitionTableData();
            }
        }
    }

    @Watch('layoutDialog')
    handleLayoutDialog() {
        this.$emit('layout-handle', this.layoutDialog);
    }

    getPostitionTableData() {
        this.loading = true;
        this.$axios
            .post('/assetSelect/assetPosition', {
                paging: this.page,
                sort: this.sort,
                fundId: this.transData.clickRow.fundId,
                fundCode: this.transData.clickRow.fundCode,
            })
            .then((res: any) => {
                if (res.total) {
                    this.tableData = res.list.slice(0, res.list.length - 1);
                    this.summary = res.list[res.list.length - 1];
                }
                this.page.total = res.total;
                this.loading = false;
            })
            .catch(() => {
                this.tableData = [];
                this.summary = {};
                this.loading = false;
            });
    }

    // 合计行
    getSummaries() {
        let arr = [];
        if (this.tableData.length) {
            let count = 0;
            let objR = this.summary;
            for (let item of this.showFieldList) {
                if (objR[item.id]) {
                    arr[count++] = numberFormat(objR[item.id], 2);
                } else {
                    arr[count++] = '--';
                }
            }
        }
        return [arr];
    }

    pageRet() {
        this.getPostitionTableData();
    }

    // 分页
    pageChange(curPage: number) {
        this.page.currentPage = curPage;
        this.getPostitionTableData();
    }

    // 排序改变
    private changeTableSort(column): void {
        this.sortProp = column.property;
        this.sortOrder = column.order;
        let sortType = column.order == 'asc' ? 'ASC' : column.order == 'desc' ? 'DESC' : '';
        this.sort = this.sortableObj[column.property] + ' ' + sortType;
        this.pageChange(1);
    }

    /**
     * 提交成功后回调
     * @param {Object} 回调数据
     */
    async onSubmit(data) {
        await this.queryLayout();
    }

    // 获取页面布局信息
    async queryLayout() {
        let resList: any = await new Promise((resolve, reject) => {
            this.$axios('/tableLayout/query/TN_ASSET_POSITION')
                .then((res: any) => {
                    resolve(res);
                })
                .catch(err => {
                    reject(err);
                });
        });
        if (!resList) {
            // 新用户初始化
            const keys = this.resetNoSelectedFieldList.map(item => item.id);
            this.showFieldList = this.tableColumns.filter(item => !keys.includes(item.id));
            const fixKeys = this.fixedFieldList.map(item => item.id);
            this.selectedFieldList = this.showFieldList.filter(item => !fixKeys.includes(item.id));
        } else {
            this.selectedFieldList = JSON.parse(resList);
            this.showFieldList = this.fixedFieldList.concat(this.selectedFieldList);
        }
        this.tableKey++;
    }

    getAlign(ele) {
        let obj = this.tableColumns.find(item => item.id == ele.id);
        return (obj && obj.align) || 'right';
    }
}
</script>
<style lang="scss" scoped>
/deep/ .vxe-table .vxe-table--body-wrapper.body--wrapper {
    height: calc(50vh - 195px) !important; //
}
</style>
